Page({
  data: {
    userInfo: {
      avatarUrl: '/images/default_avatar.png',
      nickName: '微信用户',
      userId: 'wx_123456789',
      registerTime: '2023-01-01',
      phone: '138****8888'
    },
    studyData: {
      courseCount: 12,
      studyHours: 56,
      continueDays: 7
    }
  },

  onLoad() {
    // 从全局或服务器获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    }
    this.loadStudyData();
  },

  // 加载学习数据
  loadStudyData() {
    wx.request({
      url: 'https://your-api.com/api/study-data',
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            studyData: res.data.data
          });
        }
      }
    });
  },

  // 更换头像
  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        // 上传到服务器
        wx.uploadFile({
          url: 'https://your-api.com/api/upload-avatar',
          filePath: tempFilePath,
          name: 'avatar',
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 200) {
              this.setData({
                'userInfo.avatarUrl': data.data.avatarUrl
              });
              wx.showToast({
                title: '头像更新成功',
                icon: 'success'
              });
            }
          }
        });
      }
    });
  },

  // 编辑昵称
  editNickname() {
    wx.showModal({
      title: '修改昵称',
      content: '请输入新的昵称',
      editable: true,
      placeholderText: this.data.userInfo.nickName,
      success: (res) => {
        if (res.confirm && res.content) {
          this.setData({
            'userInfo.nickName': res.content
          });
          // 调用API更新昵称
          wx.request({
            url: 'https://your-api.com/api/update-nickname',
            method: 'POST',
            data: {
              nickname: res.content
            },
            success: (updateRes) => {
              if (updateRes.data.code === 200) {
                wx.showToast({
                  title: '昵称更新成功',
                  icon: 'success'
                });
              }
            }
          });
        }
      }
    });
  },

  // 修改手机号
  changePhone() {
    wx.navigateTo({
      url: '/pages/settings/change-phone'
    });
  },

  // 修改密码
  changePassword() {
    wx.navigateTo({
      url: '/pages/settings/change-password'
    });
  },

  // 退出登录
  showLogoutConfirm() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token');
          getApp().globalData.userInfo = null;
          wx.reLaunch({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
});